//==============引入模块==================
let createError = require('http-errors'),
  express = require('express'),
  path = require('path'),
  os = require('os'),
  cookieParser = require('cookie-parser'),
  logger = require('morgan'),
  bodyParser = require('body-parser'),
  cors = require("cors"),//解决跨域问题

  config = require(__dirname + '/config'),//配置文件

  routers = require(__dirname + '/routers'),//接口路由地址
  notFind = require(__dirname + '/middlewares/not-find');//引入自定义的中间件

let app = express(),
  router = express.Router(),
  port = config.SERVER_PORT;

//==============解決跨域的问题==================
app.use(cors({
  methods: ["GET", "POST"],
  alloweHeaders: [
    "Content-Type", "application/x-www-form-urlencoded;application/json;charset=utf-8",
    "X-Powered-By", "node-express"
  ]
}));

//==============设置模板引擎==================
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

//==============载入中间件==================
app.use(bodyParser.json());// parse application/json
app.use(bodyParser.urlencoded({extended: false}));// parse application/x-www-form-urlencoded

//  app.use('/api', router);//引入router中间件并设置路由接口地址前缀
app.use(logger('dev'));

app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));//静态html文件

//==============应用==================
// 访问路由地址
// app.use(routers);
app.use("/api",routers);//接口 (访问地址: http://localhost:3000/api/...);

app.use("/hello",function(req, res, next){//访问地址: http://localhost:3000/hello
  res.json({
    msg: "helloWorld",
    status: 200,
    data: [1, 2, 3]
  });
  //next();//next的解释：https://expressjs.com/zh-cn/guide/writing-middleware.html
});

//首页地址（一般会去掉他，只是给你访问看的）
app.get('/', (req, res, next) => {
  res.render('index', {title: 'Express'});
});

//==============错误处理==================
// 引用自定义404错误处理中间件
app.use(notFind);

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
// const Index = require(config.ROOT_PATH + '/controller/index');//引入控制器
// app.use("/",Index);

//==============启动服务==================
app.listen(port, function () {
  //console.log("Example app listening on port " + port);
  console.log('  App running at:');
  console.log("  - Local: http://localhost:" + port);
  console.log("  - Network: http://" + getLocalIP() + ":" + port);
});

function getLocalIP() { //获取IP地址
  const WLAN = ((os.networkInterfaces()).WLAN)[1];
  return WLAN.address;
}

